package org.finalministry.database.dao;

import java.util.List;

import javax.persistence.Query;

import org.apache.commons.collections.ListUtils;
import org.finalministry.objects.Contact;
import org.hibernate.HibernateException;

public class ContactDAO extends AbstractDAO {

	private static final String TABLENAME = "contact";

	public ContactDAO() {
		super();
	}

	/**
	 * Insert a new Contact into the database.
	 * 
	 * @param Contact
	 * @return persisted ID
	 * @throws DataAccessLayerException
	 */
	public Contact merge(Contact contact) throws DataAccessLayerException {

		return (Contact) super.merge(contact);
	}

	/**
	 * Delete a detached Contact from the database.
	 * 
	 * @param Contact
	 */
	public void delete(Contact contact) throws DataAccessLayerException {

		super.delete(contact);
	}

	/**
	 * Find an Contact by its primary key.
	 * 
	 * @param id
	 * @return
	 */
	public Contact find(Long id) throws DataAccessLayerException {

		return (Contact) super.find(Contact.class, id);
	}

	/**
	 * Finds all Contacts in the database.
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Contact> findAll() throws DataAccessLayerException {

		return super.findAll(Contact.class);
	}

	/**
	 * Get table name
	 */
	@Override
	protected String getTableName() {

		return TABLENAME;
	}

	@SuppressWarnings("unchecked")
	public List<Contact> getAllByTerritoryID(Long id) {

		List<Contact> results = ListUtils.EMPTY_LIST;

		try {
			startOperation();

			Query query = em.createNativeQuery("select * from contact where territoryid = " + String.valueOf(id));
			results = query.getResultList();
			em.getTransaction().commit();
			return results;
		} catch (HibernateException e) {
			handleException(e);
			return results;
		} finally {
			em.close();
		}

	}

}
